# -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 15:59:34 2018

@author: Ricardolcf
自己通过多种方式实现两个csv根据相同字段合并成一个新表的功能
"""


def joinPyZero(s,g,field,m="full"):
    #传统方式进行join
    #s:源图层；g:目标图层；field:基于字段；savepath:保存位置；m:模式
    #s，g中都应该有相同的field字段
    #有\n，匹配最好不要最后一位
    savepath="D:/GeoData/textJoin.csv"
    total_dat=[0,0,0]#分别为：len(s);len(g),s中匹配正确的个数
    no_g_ma=[]#s中不符合的匹配，目前的代码不能统计g中不符合的内容
    s_lst=[]
    g_lst=[]
    s_index=-1#field字段所在索引
    g_index=-1
    
    with open(g,'r',encoding="utf-8") as gf:
        g_lines=gf.readlines()
        total_dat[1]=len(g_lines)-1
        for i in g_lines:
            j=i.strip('\n').split(',')
            if len(j)==1:
                j=i.strip('\n').split('\t')
            if g_index==-1:
                for k in range(len(j)):
                    if j[k]==field:
                        g_index=k
                        print(k,j[k])
                        break
            g_lst.append(j)        
    with open(s,'r',encoding="utf-8") as sf:
        s_lines=sf.readlines()
        total_dat[0]=len(s_lines)-1
        for i in s_lines:
            j=i.strip('\n').split(',')
            if len(j)==1:
                j=i.strip('\n').split('\t')
            if s_index==-1:
                for k in range(len(j)):
                    print(j)
                    if j[k]==field:
                        s_index=k
                        print(k,j[k])
                        break
            for p in range(0,total_dat[1]):
            #for gline in g_lst:#原先是用这个的
                if g_lst[p][g_index]==j[s_index]:
                    j.extend(g_lst[p])
                    total_dat[2]+=1
                    break
                if p==total_dat[1]-1:
                    no_g_ma.append(j[s_index])
            s_lst.append(j)
    
    writeToCsv(s_lst,savepath)
    print(no_g_ma)
    print('end')
    
def writeToCsv(two_dm,out_path):
    with open(out_path,'w+',encoding="utf-8") as outf:
        #k=len(two_dm[0])
        for one in two_dm:
            o_str=','.join(one)
            outf.write(o_str+'\n')

def joinWithPd(s,g,field,m="full"):            
    import pandas as pd
    s_arr=pd.read_csv(s,'\t')
    g_arr=pd.read_csv(g,',')
    g_index=g_arr.columns.drop(field)
    s_arr.append(['0'],columns=g_index)
    #print(s_arr[0:3])
    #print(g_arr['city'][0:3])
    #s_arr['num'][0]='1'
    print(s_arr[0:5])
    #for sline in s_arr[field]:
        
        #for gl in g_arr[field]:
            #if gl==sline:
                
    
    
if __name__ == '__main__':
    #MontyHallsmlt()
    #sumMANHY()
    s="D:/GeoData/chinaCityAll.csv"
    g="D:/GeoData/2017各线城市处理用291.csv"
    g1="D:/GeoData/cityTry2017fenji.csv"
    joinWithPd(s,g1,'city')
